<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="isUpdate ? t('action.edit') : t('action.create')" @ok="handleSubmit" :width="700">
    <BasicForm @register="registerForm" />
    <template #appendFooter>
      <a-button type="primary" @click="saveAndNext">{{ t('action.saveAndNext') }}</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref,unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n'
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './ltrt.data';
  import { saveOrUpdate, getById } from './ltrt.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const { t } = useI18n()
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    //labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //获取详情
      data.record = await getById({ id: data?.record?.id });
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  /**
   * 保存并继续
   */
  function saveAndNext(){
    handleSubmit(false)
  }

  //表单提交事件
  async function handleSubmit(data) {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      if (data) {
        closeModal()
      }else{
        resetFields()
      }
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

